﻿using AiXiu.BLL;
using AiXiu.Common;
using AiXiu.IBLL;
using AiXiu.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AiXiu.Web
{
    public partial class PersonalEdit : System.Web.UI.Page
    {
        private District district;
        private ListItem listltem = new ListItem("- 请选择 -", "");

        public PersonalEdit()
        {
            //加载省市信息 FileStream 类对文件系统上的文件进行读取、写入、打开和关闭操作
            //StreamReader类用于文本文件的读取    StreamWriter类用于文本文件的写入
            using (FileStream fileStream = new FileStream(Server.MapPath("~/App_Data/district.json"), FileMode.Open))
            {
                //读取文件流
                using (StreamReader streamReader = new StreamReader(fileStream, Encoding.Default))
                {
                    string distictString = streamReader.ReadToEnd();
                    //JsonConvert.DeserializeObject<District> json反序列化
                    district = JsonConvert.DeserializeObject<District>(distictString);
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //页面初始化，读取登录用户信息，从IdentityManager类中获取用户信息
                TBUsers tBUsers = IdentityManager.ReadUser();
                //显示用户资料
                if (tBUsers != null)
                {
                    //显示用户默认值（昵称、性别、生日年月日yyyy - MM - dd）
                    //txtNickName.Text = tBUsers.NickName;
                    //ddlSex.SelectedValue = tBUsers.Sex.ToString();
                    //if (tBUsers.Birthday != null)
                    //{
                    //    txtBirthday.Text = tBUsers.Birthday.Value.ToString("yyyy-MM-dd");
                    //}
                    //
                    //显示用户默认值（昵称、性别、生日年月日yyyy-MM-dd）
                    //空合并运算符 a ?? b  当a为null时返回b，a不为null时返回a本身  
                    txtNickName.Text = tBUsers.NickName ?? $"用户{tBUsers.Id}";//$"用户{tBUsers.Id}" 相当与用户+id
                    ddlSex.SelectedValue = tBUsers.Sex.ToString();
                    //三元运算符 x?y:z    如果表达式x为true,则返回y  如果x为false，则返回z
                    txtBirthday.Text = tBUsers.Birthday.HasValue ? tBUsers.Birthday.Value.ToString("yyyy-MM-dd") : "";

                    //获取爱好字符串分离出爱好数组，循环遍历前台复选框中的值，包含一个设置属性选中一个
                    if (!string.IsNullOrWhiteSpace(tBUsers.Hobby))
                    {
                        //分割爱好
                        string[] h0bbyList = tBUsers.Hobby.Split(' ');
                        //循环
                        for (int i = 0; i < cblHobby.Items.Count; i++)
                        {
                            //h0bbyList数组包含Contains
                            if (h0bbyList.Contains(cblHobby.Items[i].Value))
                            {
                                cblHobby.Items[i].Selected = true;
                            }
                        }
                    }
                    if (!string.IsNullOrWhiteSpace(tBUsers.Address))
                    {
                        //分割地址
                        string[] cityList = tBUsers.Address.Split(' ');
                        //判断如果成功取值
                        if (cityList.Length > 1)
                        {
                            string city = cityList[1];
                            string proName = cityList[0];
                            //设置默认选中值
                            BindProvinces(proName);
                            BindCitys(proName, city);
                        }
                        else
                        {
                            BindProvinces();
                        }
                    }
                    else
                    {
                        //不设置默认选中值
                        BindProvinces();
                    }
                }
                else
                {
                    Response.Redirect("Login.aspx");
                }
            }
        }
        /// <summary>
        /// 省份选项索引变更事件
        /// </summary>
        protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
        {
            //获取选中省份名称
            string provinceName = this.ddlProvince.SelectedValue;
            //调用城市列表
            BindCitys(provinceName);
        }
        /// <summary>
        /// 绑定省份下拉列表
        /// </summary>
        /// <param name="provinceName">省份名称</param>
        private void BindProvinces(string provinceName = null)
        {
            //绑定省份列表
            this.ddlProvince.DataSource = district.Provinces;//展示城市信息
            this.ddlProvince.DataValueField = "ProvinceName";
            this.ddlProvince.DataTextField = "ProvinceName";
            this.ddlProvince.DataBind();
            this.ddlProvince.Items.Insert(0, listltem);
            //设置省份默认选中项
            if (string.IsNullOrWhiteSpace(provinceName))
            {
                this.ddlProvince.SelectedIndex = 0;
            }
            else
            {
                this.ddlProvince.SelectedValue = provinceName;
            }
        }
        /// <summary>
        /// 绑定城市下拉列表
        /// </summary>
        /// <param name="provinceName">省份名称</param>
        /// <param name="CityName">城市名称</param>
        private void BindCitys(string provinceName, string CityName = null)
        {
            //为选择省份名称时，清空城市列表
            if (string.IsNullOrWhiteSpace(provinceName))
            {
                this.ddlCity.Items.Clear();
                this.ddlCity.Items.Add(listltem);
                return;
            }
            //未找到省份名称时，清空城市列表
            Province province = district.Provinces.SingleOrDefault(m => m.ProvinceName == provinceName);
            if (province == null)
            {
                this.ddlCity.Items.Clear();
                this.ddlCity.Items.Add(listltem);
            }
            //绑定城市列表
            this.ddlCity.DataSource = province.Citys;
            this.ddlCity.DataValueField = "CityName";
            this.ddlCity.DataTextField = "CityName";
            this.ddlCity.DataBind();
            this.ddlCity.Items.Insert(0, listltem);
            //设置城市默认选中项
            if (string.IsNullOrWhiteSpace(CityName))
            {
                this.ddlCity.SelectedIndex = 0;
            }
            else
            {
                this.ddlCity.SelectedValue = CityName;
            }
        }
        protected void btnProfile_Click(object sender, EventArgs e)
        {
            //读取当前用户在页面输入的信息，从IdentityManager类中获取用户信息
            TBUsers tBUsers = IdentityManager.ReadUser();
            //
            tBUsers.NickName = txtNickName.Text;
            tBUsers.Sex = ddlSex.SelectedIndex;
            if (!string.IsNullOrEmpty(txtBirthday.Text))
            { 
                tBUsers.Birthday = DateTime.Parse(txtBirthday.Text);
            }
            tBUsers.Address = $"{ddlProvince.SelectedValue} {ddlCity.SelectedValue}";
            //定义一个空集合hobbyList，把页面获取到的信息存入集合
            List<string> hobbyList = new List<string>();
            foreach (ListItem listItem in cblHobby.Items)
            {
                if (listItem.Selected)
                    hobbyList.Add(listItem.Value);
            }
            tBUsers.Hobby = string.Join(" ",hobbyList);
            //在数据库更新信息
                IUserManager userManager = new UserManager();
            OperResult<TBUsers> operResult = userManager.EditwithoutAvatar(tBUsers);
            if (operResult.StatusCode == StatusCode.Succeed)
            {
                //更新用户缓存信息
                IdentityManager.SaveUser(tBUsers);
                Response.Redirect("personal.aspx");
            }
            else
            {
                this.Alert("editerror", operResult.Message);
            }
        }
    }
}